package com.xunwulian.weixin.h5.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xunwulian.api.iface.AppAPI;
import com.xunwulian.api.iface.CardAPI;
import com.xunwulian.api.iface.SmsAPI;
import com.xunwulian.base.constant.CmebEntity;
import com.xunwulian.base.entity.AppEntity;
import com.xunwulian.base.entity.CardInfoEntity;
import com.xunwulian.base.entity.Page;
import com.xunwulian.base.exception.ErrorCodeException;
import com.xunwulian.cmeb.service.CmebUtil;
import com.xunwulian.weixin.h5.constant.ResultType;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 查询类
 */
@RestController
@RequestMapping(value = "/appqry")
public class IntAppQryController {

    private static final Logger logger = LoggerFactory.getLogger(IntAppQryController.class);

    @Reference
    private SmsAPI smsAPI;
    @Reference
    private CardAPI cardAPI;
    @Reference
    private AppAPI appAPI;

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    /**
     * APP查询SMS短信和GPRS历史使用情况
     * <p>
     * 参数： msisdn: 卡号， 非必输，不输则表示全部卡 type: sms or gprs，必输 date_s，非必输
     * date_e，非必输，不输，默认30天
     */
    @Deprecated
    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "/qryusedbydate")
    @ResponseBody
    public Map<String, Object> qryusedbydate(@RequestParam("msisdn") String msisdn,
                                             @RequestParam("startDate") Date startDate,
                                             @RequestParam("endDate") Date endDate) {

        logger.info("APP查询SMS短信和GPRS历史使用情况，msisdn:" + msisdn + "开始时间 startDate:" + startDate + ",结束时间 endDate:" + endDate);

//        SmsGprsBalanceEntity entity = smsGprsBalanceDao.queryUsedByDate(msisdn, startDate, endDate);

        Map<String, Object> map = new HashMap();
//        map.put("entity", entity);
        map.put("result", ResultType.SUCCESS.getType());

        return map;
    }

    /**
     * APP查询码号信息
     * <p>
     * 参数： card_info: 所查询卡的 msisdn、imsi 或 iccid type: 0—msisdn 1—imsi 2—iccid
     */
    @Deprecated
    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "/qrycardinfo")
    @ResponseBody
    public Map<String, Object> qrycardinfo(@Param("type") int type,
                                           @Param("value") String value) {

        // TODO 重构
        CardInfoEntity entity = cardAPI.getByMsisdn(value);

        Map<String, Object> map = new HashMap();
        if (entity == null) {
            map.put("code", ResultType.NOT_EXISTS.getType());
        }

        map.put("entity", entity);

        return map;
    }

    /**
     * APP查询汇总信息：余额、当月短信使用情况、当月流量使用情况
     * 开关机、卡的用户状态、GPRS在线信息
     */
    @Deprecated
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, value = "/queryinfo")
    public Map<String, Object> queryInfo(@RequestParam(name = "msisdn") String msisdn) {

        Map<String, Object> map = new HashMap();

        CardInfoEntity cardInfoEntity = cardAPI.getByMsisdn(msisdn);
        if(cardInfoEntity == null) {
            map.put("code", ResultType.CARDINFO_INVALID.getType());
        }

        // TODO 异常处理
        AppEntity appEntity = (AppEntity) appAPI.getApp(cardInfoEntity.getAppId()).getData();

        CmebEntity cmebEntity = null;
        try {
            CmebUtil cmebUtil = new CmebUtil();
            cmebEntity = cmebUtil.queryCardInfo(msisdn, appEntity);
        } catch (ErrorCodeException e) {
            e.printStackTrace();
        }

        if (cmebEntity == null) {
            map.put("code", ResultType.NOT_EXISTS.getType());
        }
        map.put("entity", cmebEntity);
        map.put("code", ResultType.SUCCESS.getType());

        return map;
    }


    /**
     * 获取卡号列表
     */
    @RequestMapping(value = "/getCardList")
    @ResponseBody
    public Map<String, Object> getCardList(@RequestParam("userId") String userId,
                                           @RequestParam("pno") int pno,
                                           @RequestParam("psize") int psize) {

        logger.info("查询卡号列表");

        Map<String, Object> resultMap = new HashMap();
        resultMap.put("result", ResultType.SUCCESS.getType());

        // 分页信息
        Page page = new Page();
        page.setCurrentPage(pno);
        page.setShowCount(psize);

//        List<CardInfoEntity> list = cardAPI.listPage(page, null, userId, null, null, 0);

        Map<String, Object> dataMap = new HashMap();
        resultMap.put("dataMap", dataMap);

        // 总页数和总条数
        resultMap.put("totalPageNum", page.getTotalPage());
        resultMap.put("totalResultNum", page.getTotalResult());


        logger.info("map:" + gson.toJson(resultMap));

        return resultMap;
    }


    /**
     * 搜索卡号，前十条
     */
    @RequestMapping(value = "/searchCard")
    @ResponseBody
    public Map<String, Object> searchCard(@RequestParam("userId") String userId,
                                          @RequestParam("searchKey") String searchKey) {

        logger.info("搜索卡号");

        Map<String, Object> resultMap = new HashMap();
        resultMap.put("result", ResultType.SUCCESS.getType());

        logger.info("map:" + gson.toJson(resultMap));

        return resultMap;

    }

}
